package rainy.file.synchronization.server.file;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import rainy.file.synchronization.config.RainyRunTime;
import rainy.file.synchronization.log.RainnyLogger;

public class TailFileRollingPolicy extends Thread {
	private static final String fileRollingSupport = RainyRunTime.getStringPropDefine("rainy.master.tail.rolling.support", "false");
	private static final String rollingPolicy = RainyRunTime.getStringPropDefine("rainy.master.tail.rolling.period", "1d0h0M0s");
	private static long lockedTime = System.currentTimeMillis();
	private static long oneDay = 24 * 60 * 60 * 1000;
	static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

	static {
		try {
			Date date = new Date(System.currentTimeMillis() + oneDay);
			lockedTime = format.parse(format.format(date)).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		while (true) {
			try {
				Thread.sleep(9999);
				if (needRolling()) {
					TailerAppender.needRolling = true;
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private boolean needRolling() {
		RainnyLogger.info("[FileRolling] time remained!" + (lockedTime - System.currentTimeMillis()));
		if (lockedTime - System.currentTimeMillis() <= 10 * 1000 && lockedTime - System.currentTimeMillis() >= 0) {
			lockedTime = lockedTime + oneDay;
			return true;
		}
		return false;
	}

	public static void main(String[] args) {
		new TailFileRollingPolicy().start();
	}

}
